/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86184
 * Date: 2023-02-24
 * Time: 18:57
 */
public class SparseArray {
    public static void main(String[] args) {
        //二维数组 转 稀疏数组 思路

        //1.创建二维数组
        int ChessArray1[][] = new int[11][11];
        ChessArray1[1][2] = 1;
        ChessArray1[2][3] = 2;
        ChessArray1[3][4] = 2;
        ChessArray1[4][5] = 1;
        System.out.println("原始二维数组");
        for (int[] row : ChessArray1) {
            for (int data : row) {
                System.out.print(data + " ");
            }
            System.out.println();
        }
        //2.遍历二维数组，得到有效数据的个数
        int sum = 0;
        for (int i = 0; i < ChessArray1.length; i++) {
            for (int j = 0; j < ChessArray1[i].length; j++) {
                if (ChessArray1[i][j] != 0) {
                    sum++;
                }
            }
        }
        //3.根据sum的值创建稀疏数组
        int sparseArr[][] = new int[sum + 1][3];
        sparseArr[0][0]=11;
        sparseArr[0][1]=11;
        sparseArr[0][2]=sum;
        //4.将二维数组中的值存入到稀疏数组中
        int count = 0;
        for (int i = 0; i < ChessArray1.length; i++) {
            for (int j = 0; j < ChessArray1[i].length; j++) {
                if (ChessArray1[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = ChessArray1[i][j];
                }
            }
        }
        System.out.println();
        System.out.println("稀疏数组");
        System.out.println("   " + "row" + " " + "col" + " " + "val");
        for (int i = 0; i < sparseArr.length; i++) {
            System.out.printf("[%d] ", i);
            for (int j = 0; j < 3; j++) {
                System.out.print(sparseArr[i][j] + "   ");
            }
            System.out.println();
        }

        //稀疏数组 转 二维数组 思路

        //1.读取稀疏数组的第一行数据
        int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
        //2.将稀疏数组中的数据存入二维数组中
        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        System.out.println();
        System.out.println("转换后二维数组");
        for (int[] row : chessArr2) {
            for (int data : row) {
                System.out.print(data + " ");
            }
            System.out.println();
        }
    }
}
